package site.koudai.cloud.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserContext {

    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_CONTEXT = new InheritableThreadLocal<>();

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL_CONTEXT.get();
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL_CONTEXT.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, Object> map) {
        THREAD_LOCAL_CONTEXT.set(map);
    }

    public static void clear() {
        THREAD_LOCAL_CONTEXT.remove();
    }

    public static void set(String key, Object value) {
        getLocalMap().put(key, value);
    }

    public static Object get(String key) {
        return getLocalMap().get(key);
    }

    public static <T> T get(String key, Class<T> clazz) {
        Object value = get(key);
        if (value == null) {
            return null;
        }
        return clazz.cast(value);
    }

    public static void remove(String key) {
        getLocalMap().remove(key);
    }

}
